package collection;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jiangwz
 * @create 2019/9/14.
 */
public class TestConcurrentHashMap {

    static ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap<>();

    static HashMap<String,String> hashMap = new HashMap<>();

    public static void main(String[] args){

        /**
         * 有并发问题
         */
//        testHashMap();

        /**
         * 无并发问题
         */
//        testConcurrentHashMap();



        // 原理  hashMap key可以为null (留到以后研究)
        /**
         * 因为hash方法默认key=null置0了
         *     static final int hash(Object key) {
         *         int h;
         *         return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
         *     }
         *  而 ConcurrentHashMap 则是 if (key == null || value == null) throw new NullPointerException();
         *  直接抛异常.
         */
        hashMap.put("1","1");
        hashMap.put("2","1");
        hashMap.put(null,"1");
        System.out.println(hashMap);
    }

    private static void testConcurrentHashMap() {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                concurrentHashMap.put(Thread.currentThread().getName() ,UUID.randomUUID().toString().substring(0,8));
                System.out.println(concurrentHashMap);
            }, "" + i).start();
        }

    }

    private static void testHashMap() {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                hashMap.put(Thread.currentThread().getName() ,UUID.randomUUID().toString().substring(0,8));
                System.out.println(hashMap);
            }, "" + i).start();
        }

    }
}
